import DataBase from '@/services/data-factory/index';
import {
  ActionType,
  PageContainer,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import type { PopconfirmProps } from 'antd';
import { Button, Divider, Drawer, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import CreateForm from './CreateForm';
import UpdateForm from './UpdateForm';
//分页类型
interface paginationType {
  pageSizeOptions: string[];
  showSizeChanger: boolean;
  total: number;
  current: number;
  pageSize: number;
}

const cancel: PopconfirmProps['onCancel'] = (e) => {
  console.log(e);
  message.error('操作取消');
};

const {
  getDatabaseListUsingPost,
  databaseReleaseUsingPut,
  deleteDatabaseUsingDelete,
} = DataBase.databaseguanlikongzhiqi;

const DataBaseManagement: React.FC<unknown> = () => {
  const [databaseId, setDatabaseId] = useState<number>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.UserInfo>();

  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState<paginationType>({
    pageSizeOptions: ['10', '20', '30'],
    showSizeChanger: true,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 在组件顶部添加
  const [selectedDbType, setSelectedDbType] = useState<string | null>(null);
  // 修改图片点击处理函数
  const handleImageClick = (index: number) => {
    const dbConfig = [
      { type: 'mysql', url: 'jdbc:mysql://localhost:3306/' },
      { type: 'oracle', url: 'jdbc:oracle:thin:@localhost:1521:' },
      { type: 'db2', url: 'jdbc:db2://localhost:50000/' },
    ];

    console.log(selectedDbType);
    const config = dbConfig[index];
    setSelectedDbType(config.type); // 记录选择的数据库类型
    history.push({
      pathname: '/create-database',
      state: { dbType: config.type, defaultUrl: config.url },
    });
  };
  // 获取码表数据列表
  const getDataBaseList = async (params = {}) => {
    const { data, code, msg } = await getDatabaseListUsingPost({
      ...params, // 传递分页、过滤等参数
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    });
    console.log(data);
    if (code === 100200) {
      setData(data.records || []); // 更新表格数据
      setPagination((prevPagination) => ({
        ...prevPagination,
        total: data.totalItems, // 更新总条数
      }));
    }
    return {
      data: data || [], // 返回查询到的数据
      code,
      message: msg, // 使用解构出来的 msg
    };
  };
  // 修改状态
  const updataeStatues = async (databaseId: number, databaseStatus: number) => {
    await databaseReleaseUsingPut({ databaseId, databaseStatus });
    // debugger;
    console.log(databaseId, databaseStatus);

    message.success('状态修改成功');
    getDataBaseList();
  };
  // 删除
  const handleDelete = async (databaseId: number) => {
    const res = await deleteDatabaseUsingDelete({ databaseId });
    if (res.code === 100200) {
      message.success('删除成功');
    } else {
      message.error('删除失败');
    }
    getDataBaseList();
  };

  const columns: ProDescriptionsItemProps<any>[] = [
    {
      title: '数据源名称',
      dataIndex: 'datasourceName',
      valueType: 'text',
    },

    {
      title: '数据库类型',
      dataIndex: 'categoryName',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '数据库类型为必填项',
          },
        ],
      },
    },
    {
      title: '数据源描述',
      dataIndex: 'datasourceDescription',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '连接信息',
      dataIndex: 'connInformation',
      // hideInTable: true,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '应用状态',
      dataIndex: 'databaseStatus',
      // hideInTable: true,
      hideInForm: true,
      valueEnum: {
        0: { text: '未发布', status: '0' },
        1: { text: '已发布', status: '1' },
        2: { text: '已停用', status: '2' },
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',

      render: (_, record) => (
        <>
          <Popconfirm
            title="测试确认"
            description="测试成功？"
            // onConfirm={() =>
            //   updataeStatues(
            //     [record.databaseId],
            //     record.databaseStatus === 0 ? 1 : 0,
            //   )
            // }
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button type="primary">连通测试</Button>
          </Popconfirm>
          <Popconfirm
            title="状态确认"
            description="你确定要修改状态吗？"
            onConfirm={() =>
              updataeStatues(
                record.databaseId,
                record.databaseStatus === 0 ? 1 : 0,
              )
            }
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            {/* {standardStatus ? '发布' : '停用'} */}
            <Button>{record.databaseStatus === 0 ? '发布' : '停用'}</Button>
          </Popconfirm>
          <Divider type="vertical" />

          <Button
            type="primary"
            onClick={() => {
              setDatabaseId(record.databaseId);
              handleModalVisible(true);
              setStepFormValues(record); // 记录当前行数据
            }}
            disabled={record.databaseStatus === 1} // 如果状态为已发布，则禁用编辑按钮
          >
            编辑
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="删除确认"
            description="你确定要删除吗？"
            onConfirm={() => {
              handleDelete(record.databaseId);
            }}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '数据库管理',
      }}
    >
      <input type="file" style={{ display: 'none' }} />
      <ProTable<API.UserInfo>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="databaseId"
        search={{
          labelWidth: 70,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              handleModalVisible(true); // 打开新增模态框
              setStepFormValues({}); // 清空初始值
            }}
          >
            新建数据源
          </Button>,
        ]}
        request={getDataBaseList}
        columns={columns}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) => {
            setPagination({
              ...pagination,
              current: page,
              pageSize: pageSize || pagination.pageSize,
            });
          },
        }}
        dataSource={data}
      />

      <CreateForm
        onClickImage={handleImageClick} // 新增传递点击事件
        onCancel={() => {
          handleModalVisible(false);
          setDatabaseId(undefined); // 关键修复：重置 codeTableId
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        onSuccess={async () => {
          // 新增成功回调
          handleModalVisible(false);
          getDataBaseList();
          setDatabaseId(undefined); // 成功提交后也需重置
          // stepFormValues.codeTableId = '';
          // setCodeTableId(0);
        }}
        getDataBaseList={getDataBaseList}
        initialValues={stepFormValues || undefined} // 传递 stepFormValues 作为 initialValues
        databaseId={databaseId} // 传递 codeTableId
      ></CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions<API.UserInfo>
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default DataBaseManagement;
